﻿using Api.Core.Common.Attributes;
using Api.Core.IRepository.IUnitOfWork;
using AspectCore.DynamicProxy;
using AspectCore.Injector;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace Api.Core.AOP
{
    //未测试
    public class TransactionAop : BaseAop
    {
        [FromContainer]
        private ISugarUnitOfWork _sugarUnitOfWork { get; set; }

        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            var method = context.ProxyMethod ?? context.ServiceMethod;

            var attribute = method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(TransactionAttribute)) as TransactionAttribute;

            if (attribute == null)
            {
                await next.Invoke(context);
                return;
            }
            try
            {
                Console.WriteLine("Before BeginTran call");
                _sugarUnitOfWork.BeginTran();

                var result = await RunAndGetReturn(context, next);

                _sugarUnitOfWork.CommitTran();
            }
            catch (System.Exception)
            {
                Console.WriteLine("Catch BeginTran call");
                _sugarUnitOfWork.RollbackTran();
                throw;
            }
            finally
            {
                Console.WriteLine("After BeginTran call");
            }
        }


    }
}
